package backtracking.combination;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 131. 分割回文串
 * <p>
 * 给你一个字符串 s，请你将 s 分割成一些子串，使每个子串都是 回文串 。返回 s 所有可能的分割方案。
 * <p>
 * 回文串 是正着读和反着读都一样的字符串。
 */
public class N131_PalindromePartitioning {
    List<List<String>> res = new LinkedList<>();
    List<String> path = new LinkedList<>();

    private boolean isPalindrome(String s, int l, int r) {
        for (int i = l, j = r; i <= j; i++, j--) {
            if (s.charAt(i) != s.charAt(j)) return false;
        }
        return true;
    }

    private void backtracking(String s, int startIndex) {
        if (startIndex >= s.length()) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i < s.length(); i++) {
            if (isPalindrome(s, startIndex, i))
                path.add(s.substring(startIndex, i + 1));
            else continue;

            backtracking(s, i + 1);
            path.remove(path.size() - 1);
        }

    }

    public List<List<String>> partition(String s) {
        backtracking(s, 0);
        return res;
    }

    public static void main(String[] args) {
        N131_PalindromePartitioning solution = new N131_PalindromePartitioning();
        List<List<String>> lists = solution.partition("aab");
        for (List<String> list : lists) {
            for (String s : list) {
                System.out.print(s + " ");
            }
            System.out.println();
        }

    }
}
